package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private MongoTemplate template;
    @Autowired
    private RegionRepository repository ;
    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        Query query = new Query();
        long count = template.count(query, Region.class);
        if(count==0){
            return Page.empty();
        }
        if(count<=qo.getPageSize()){
            qo.setCurrentPage(1);
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "id");
        query.with(pageable);
        List<Region> regions = template.find(query, Region.class);
        return new PageImpl<>(regions,pageable , count);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(StringUtils.hasLength(region.getId())){
            this.update(region);
        }else{
            this.save(region);
        }
    }

    @Override
    public List<Region> queryHotRegion() {
        List<Region> list = repository.findByIshotOrderBySequence(Region.STATE_HOT);
        return list;
    }

}
